/*
 * Copyright 2017, The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ctyon.watchmanager;

import android.app.Application;
import android.content.Context;

import com.alibaba.android.arouter.launcher.ARouter;
import com.ctyon.common.config.glid.GlideApp;
import com.ctyon.common.container.BeanContainer;
import com.ctyon.common.util.SPUtils;
import com.ctyon.netlibrary.utils.ApiConfig;
import com.ctyon.watchmanager.config.CustomImageLoader;
import com.ctyon.watchmanager.model.db.AppDatabase;
import com.ctyon.watchmanager.model.net.entity.Manager;
import com.ctyon.watchmanager.model.net.entity.Watch;
import com.ctyon.watchmanager.util.LogUtil;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.DiskLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.previewlibrary.ZoomMediaLoader;
import com.squareup.leakcanary.LeakCanary;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;

import androidx.annotation.Nullable;
import androidx.multidex.MultiDex;

import static com.ctyon.watchmanager.model.net.NetConfig.BASE_URL_TEST;

/**
 * Android Application class. Used for accessing singletons.
 */
public class BasicApp extends Application {

    private static BasicApp basicApp;

    private AppExecutors mAppExecutors;
    private BeanContainer beanContainer;

    private Manager manager;
    private Watch watch;

    @Override
    public void onCreate() {
        super.onCreate();

        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);

        basicApp = this;
        mAppExecutors = new AppExecutors();
        beanContainer = new BeanContainer();

        /**
         * 注意: 即使您已经在AndroidManifest.xml中配置过appkey和channel值，也需要在App代码中调
         * 用初始化接口（如需要使用AndroidManifest.xml中配置好的appkey和channel值，
         * UMConfigure.init调用中appkey和channel参数请置为null）。
         */
        UMConfigure.init(basicApp, UMConfigure.DEVICE_TYPE_PHONE, null);
        // 选用AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        UMConfigure.setLogEnabled(true);

        //初始化日志
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(true)//（可选）是否显示线程信息。 默认值为true
                .methodCount(0)// （可选）要显示的方法行数。 默认2
                //.methodOffset(7)// （可选）设置调用堆栈的函数偏移值，0的话则从打印该Log的函数开始输出堆栈信息，默认是0
                //.logStrategy(customLog)//（可选）更改要打印的日志策略。 默认LogCat
                .tag("WATCHMANAGER_LOGGER")//（可选）每个日志的全局标记。 默认PRETTY_LOGGER（如上图）
                .build();
        Logger.addLogAdapter(new DiskLogAdapter());//(可选) 保存日志到文件 /storage/emulated/0
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy){
            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return BuildConfig.DEBUG;
            }
        });

        //初始化ARouter
        if (BuildConfig.DEBUG) {// 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();// 打印日志
            ARouter.openDebug();// 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(basicApp);// 尽可能早，推荐在Application中初始化

        //初始化网络请求模块
        new ApiConfig.Builder()
                .setBaseUrl(BASE_URL_TEST)//BaseUrl，这个地方加入后项目中默认使用该url
                .setInvalidateToken(300)//Token失效码
                .setSucceedCode(200)//成功返回码  NBA的测试返回成功code为0  上传图片返回code为200 由于是不同接口 请大家注意
                .setFilter("action.token.timeout")//失效广播Filter设置
                //.setDefaultTimeout(2000)//响应时间，可以不设置，默认为2000毫秒
                //.setHeads(headMap)//动态添加的header，也可以在其他地方通过ApiConfig.setHeads()设置
                //.setOpenHttps(true)//开启HTTPS验证
                //.setSslSocketConfigure(sslSocketConfigure)//HTTPS认证配置
                .build()
                .init(basicApp.getApplicationContext());

        //初始化SharedPreferences
        SPUtils.getInstance(basicApp.getApplicationContext(), "");

        //初始化ImageSelect
        ISNav.getInstance().init((ImageLoader) (context, path, imageView) -> GlideApp.with(context).load(path).into(imageView));

        ZoomMediaLoader.getInstance().init(new CustomImageLoader());
    }

    public AppDatabase getDatabase() {
        return AppDatabase.getInstance(this, mAppExecutors);
    }

    public DataRepository getRepository() {
        return DataRepository.getInstance(getDatabase());
    }

    public AppExecutors getAppExecutors() {
        return mAppExecutors;
    }

    public static BasicApp getInstance() {
        return basicApp;
    }

    public BeanContainer getBeanContainer() {
        return beanContainer;
    }

    public Manager getManager() {
        return manager;
    }

    public void setManager(Manager manager) {
        this.manager = manager;
    }

    public Watch getWatch() {
        return watch;
    }

    public void setWatch(Watch watch) {
        this.watch = watch;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
